<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */
namespace MoChat\Plugin\RoomTodo\Queue;

use Hyperf\AsyncQueue\Annotation\AsyncQueueMessage;
use Hyperf\Contract\StdoutLoggerInterface;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Utils\Codec\Json;
use MoChat\App\Corp\Contract\CorpContract;
use MoChat\App\Corp\Logic\AppTrait;
use MoChat\App\Utils\Url;
use MoChat\App\WorkAgent\QueueService\MessageRemind;
use MoChat\App\WorkRoom\Contract\WorkRoomContract;
use MoChat\Plugin\RoomTodo\Contract\RoomTodoContract;

/**
 * 企业微信 待办提醒
 * Class TodoRemindQueue.
 */
class TodoRemindQueue
{
    use AppTrait;

    /**
     * @Inject
     * @var RoomTodoContract
     */
    protected $roomTodo;

    /**
     * @Inject
     * @var WorkRoomContract
     */
    protected $workRoom;

    /**
     * @Inject
     * @var CorpContract
     */
    protected $corpContract;

    /**
     * @Inject
     * @var StdoutLoggerInterface
     */
    private $logger;

    /**
     * @AsyncQueueMessage(pool="remind")
     * @param $corpId
     */
    public function handle($corpId): void
    {
        $todos = $this->roomTodo->getRoomTodoByCorpId($corpId, ['id', 'room_id', 'employee_ids', 'content', 'day', 'time', 'wx_user_id']);
        foreach ($todos as $todo) {
            if (date('Y-m-d') !== $todo['day'] || date('H:i') !== $todo['time']) {
                continue;
            }
            $room = $this->workRoom->getWorkRoomById($todo['roomId'], ['name']);
            $wxUserIds = Json::decode($todo['wxUserId']);
            $employeeIds = Json::decode($todo['employeeIds']);
            foreach ($wxUserIds as $K => $wxUserId) {
                $this->sendRemind($corpId, $todo['roomId'], $employeeIds[$K], $room['name'], $wxUserId, $todo['content']);
            }
            $this->roomTodo->updateRoomTodoById($todo['id'], ['status' => 1]);
        }
    }

    /**
     * 发送提醒.
     * @param $corpId
     * @param $roomId
     * @param $employeeId
     * @param $roomName
     * @param $wxUserId
     * @param $content
     */
    protected function sendRemind($corpId, $roomId, $employeeId, $roomName, $wxUserId, $content)
    {
//        $url = Url::getSidebarBaseUrl() . '/batchAddFriend?employeeId=' . $employeeId . '&roomId=' . $roomId;
        $time = date('Y-m-d H:i');
        $text = "【待办提醒】您有新的待办事项哦！\n" .
            "群名称：{$roomName}\n" .
            "待办事项：{$content}\n" .
            "提醒时间：{$time}\n";
//            "<a href='{$url}'>点击查看群聊详情</a>";
        $messageRemind = make(MessageRemind::class);
        $messageRemind->sendToEmployee(
            $corpId,
            $wxUserId,
            'text',
            $text
        );
    }
}
